<template>
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="800px"
    :before-close="handleClose"
    class="audit-dialog"
    :close-on-click-modal="false"
    destroy-on-close>

    <div class="audit-content">
      <!-- 审核信息展示 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="header-left">
              <div class="header-icon" :class="getAuditIconClass()">
                <i :class="getAuditIcon()"></i>
              </div>
              <span class="header-title">{{ dialogTitle }}</span>
            </div>
            <div class="header-right">
              <el-tag :type="getAuditTypeTag()" size="large">
                {{ getAuditTypeText() }}
              </el-tag>
            </div>
          </div>
        </template>

        <!-- 选中的成绩统计 -->
        <div class="selection-summary">
          <div class="summary-item">
            <div class="summary-number">{{ scores.length }}</div>
            <div class="summary-label">选中记录</div>
          </div>
          <div class="summary-item">
            <div class="summary-number">{{ getProjectCount() }}</div>
            <div class="summary-label">涉及项目</div>
          </div>
          <div class="summary-item">
            <div class="summary-number">{{ getStudentCount() }}</div>
            <div class="summary-label">涉及学生</div>
          </div>
        </div>

        <!-- 成绩列表 -->
        <div class="selected-scores">
          <el-table
            :data="scores"
            stripe
            border
            size="default"
            max-height="300"
            empty-text="暂无数据"
            highlight-current-row>
            <el-table-column type="index" label="#" width="50" align="center"></el-table-column>
            <el-table-column prop="project.name" label="项目名称" min-width="140" show-overflow-tooltip>
              <template #default="scope">
                <div class="project-cell">
                  <i class="el-icon-trophy project-icon"></i>
                  <span>{{ scope.row.project?.name || '-' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="student.realName" label="学生姓名" width="120" align="center">
              <template #default="scope">
                <el-link type="primary" :underline="false" @click="handleStudentClick(scope.row.student)">
                  {{ scope.row.student?.realName || '-' }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="scoreValue" label="成绩值" width="120" align="center">
              <template #default="scope">
                <div class="score-cell" :class="getScoreClass(scope.row)">
                  <span class="score-value">{{ formatScore(scope.row.scoreValue) }}</span>
                  <span class="score-unit">{{ scope.row.unit }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="当前状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)" size="small" effect="dark">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="ranking" label="排名" width="80" align="center">
              <template #default="scope">
                <div v-if="scope.row.ranking" class="ranking-badge" :class="getRankingClass(scope.row.ranking)">
                  {{ scope.row.ranking }}
                </div>
                <span v-else class="text-placeholder">-</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 审核表单 -->
      <el-card class="form-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="header-title">
              <i class="el-icon-edit"></i> 审核信息
            </span>
          </div>
        </template>

        <el-form
          :model="auditForm"
          :rules="auditFormRules"
          ref="auditFormRef"
          label-width="100px"
          size="small">

          <el-form-item label="审核结果" prop="result">
            <el-radio-group v-model="auditForm.result" @change="handleResultChange">
              <el-radio v-if="auditType === 'approve'" label="通过">通过</el-radio>
              <el-radio v-if="auditType === 'reject'" label="驳回">驳回</el-radio>
              <el-radio v-if="auditType === 'publish'" label="公示">公示</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="审核意见" prop="remark">
            <el-input
              v-model="auditForm.remark"
              type="textarea"
              :rows="4"
              :placeholder="getRemarkPlaceholder()"
              maxlength="500"
              show-word-limit>
            </el-input>
          </el-form-item>

          <!-- 审核选项 -->
          <el-form-item v-if="auditType === 'approve'" label="后续操作" prop="nextAction">
            <el-checkbox-group v-model="auditForm.nextActions">
              <el-checkbox label="publish">审核通过后立即公示</el-checkbox>
              <el-checkbox label="notify">向学生发送通知</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item v-if="auditType === 'reject'" label="驳回原因" prop="rejectReason">
            <el-select
              v-model="auditForm.rejectReason"
              placeholder="请选择驳回原因"
              style="width: 100%">
              <el-option
                v-for="reason in rejectReasons"
                :key="reason.value"
                :label="reason.label"
                :value="reason.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-if="auditType === 'publish'" label="公示范围" prop="publishScope">
            <el-radio-group v-model="auditForm.publishScope">
              <el-radio label="public">全校公开</el-radio>
              <el-radio label="internal">仅内部公开</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 审核须知 -->
      <el-alert
        :title="getAlertTitle()"
        :type="getAlertType()"
        :closable="false"
        show-icon
        class="audit-alert">
        <template #default>
          <ul class="alert-content">
            <li v-for="(item, index) in getAlertContent()" :key="index">{{ item }}</li>
          </ul>
        </template>
      </el-alert>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ getSubmitButtonText() }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'AuditDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    auditType: {
      type: String,
      default: 'approve' // approve, reject, publish
    },
    scores: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'close', 'confirm', 'student-click'],
  setup(props, { emit }) {
    // 响应式数据
    const submitLoading = ref(false)
    const auditFormRef = ref(null)
    const auditForm = ref({
      result: '',
      remark: '',
      rejectReason: '',
      publishScope: 'public',
      nextActions: []
    })

    // 表单验证规则
    const auditFormRules = {
      result: [
        { required: true, message: '请选择审核结果', trigger: 'change' }
      ],
      remark: [
        { required: true, message: '请输入审核意见', trigger: 'blur' },
        { min: 5, message: '审核意见至少5个字符', trigger: 'blur' },
        { max: 500, message: '审核意见不能超过500个字符', trigger: 'blur' }
      ],
      rejectReason: [
        { required: true, message: '请选择驳回原因', trigger: 'change' }
      ],
      publishScope: [
        { required: true, message: '请选择公示范围', trigger: 'change' }
      ]
    }

    // 驳回原因选项
    const rejectReasons = [
      { value: 'data_error', label: '数据错误' },
      { value: 'format_wrong', label: '格式不正确' },
      { value: 'missing_info', label: '信息不完整' },
      { value: 'score_unreasonable', label: '成绩不合理' },
      { value: 'violation', label: '违反规则' },
      { value: 'technical_issue', label: '技术问题' },
      { value: 'other', label: '其他原因' }
    ]

    // 计算属性
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })

    const dialogTitle = computed(() => {
      const titleMap = {
        'approve': '成绩审核',
        'reject': '成绩驳回',
        'publish': '成绩公示'
      }
      return titleMap[props.auditType] || '成绩审核'
    })

    // 统计方法
    const getProjectCount = () => {
      const projects = new Set(props.scores.map(score => score.project?.name).filter(Boolean))
      return projects.size
    }

    const getStudentCount = () => {
      const students = new Set(props.scores.map(score => score.student?.realName).filter(Boolean))
      return students.size
    }

    // 样式类方法
    const getAuditIcon = () => {
      const iconMap = {
        'approve': 'el-icon-check',
        'reject': 'el-icon-close',
        'publish': 'el-icon-view'
      }
      return iconMap[props.auditType] || 'el-icon-edit'
    }

    const getAuditIconClass = () => {
      const classMap = {
        'approve': 'success',
        'reject': 'danger',
        'publish': 'primary'
      }
      return classMap[props.auditType] || 'info'
    }

    const getAuditTypeTag = () => {
      const tagMap = {
        'approve': 'success',
        'reject': 'danger',
        'publish': 'primary'
      }
      return tagMap[props.auditType] || 'info'
    }

    const getAuditTypeText = () => {
      const textMap = {
        'approve': '审核通过',
        'reject': '审核驳回',
        'publish': '成绩公示'
      }
      return textMap[props.auditType] || '审核处理'
    }

    const getStatusTagType = (status) => {
      const statusMap = {
        '待审核': 'warning',
        '已公示': 'success',
        '已驳回': 'danger',
        '有异议': 'info'
      }
      return statusMap[status] || 'info'
    }

    const getScoreClass = (row) => {
      if (row.ranking === 1) return 'gold-score'
      if (row.ranking === 2) return 'silver-score'
      if (row.ranking === 3) return 'bronze-score'
      return ''
    }

    const getRankingClass = (ranking) => {
      if (ranking === 1) return 'gold'
      if (ranking === 2) return 'silver'
      if (ranking === 3) return 'bronze'
      return 'normal'
    }

    // 格式化方法
    const formatScore = (value) => {
      if (value === null || value === undefined) return '-'
      return typeof value === 'number' ? value.toFixed(2) : value
    }

    // 事件处理方法
    const handleStudentClick = (student) => {
      emit('student-click', student)
    }

    const handleResultChange = () => {
      // 可以根据不同的审核结果调整表单
    }

    const handleClose = () => {
      emit('close')
      resetForm()
    }

    const handleSubmit = async () => {
      if (!auditFormRef.value) return

      try {
        await auditFormRef.value.validate()

        submitLoading.value = true

        // 构建提交数据
        const submitData = {
          type: props.auditType,
          scoreIds: props.scores.map(score => score.id),
          result: auditForm.value.result,
          remark: auditForm.value.remark,
          ...auditForm.value
        }

        // 模拟提交过程
        await new Promise(resolve => setTimeout(resolve, 1500))

        emit('confirm', submitData)
        handleClose()
        ElMessage.success('操作成功')
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        submitLoading.value = false
      }
    }

    // 重置表单
    const resetForm = () => {
      auditForm.value = {
        result: '',
        remark: '',
        rejectReason: '',
        publishScope: 'public',
        nextActions: []
      }
      if (auditFormRef.value) {
        auditFormRef.value.resetFields()
      }
    }

    // 工具方法
    const getRemarkPlaceholder = () => {
      const placeholderMap = {
        'approve': '请输入审核通过的理由...',
        'reject': '请输入审核驳回的详细原因...',
        'publish': '请输入公示说明...'
      }
      return placeholderMap[props.auditType] || '请输入审核意见...'
    }

    const getAlertTitle = () => {
      const titleMap = {
        'approve': '审核通过须知',
        'reject': '审核驳回须知',
        'publish': '成绩公示须知'
      }
      return titleMap[props.auditType] || '审核须知'
    }

    const getAlertType = () => {
      const typeMap = {
        'approve': 'success',
        'reject': 'warning',
        'publish': 'info'
      }
      return typeMap[props.auditType] || 'info'
    }

    const getAlertContent = () => {
      const contentMap = {
        'approve': [
          '审核通过后，成绩状态将变更为"已通过"',
          '学生可在系统中查看已通过的成绩',
          '后续可以进行成绩公示操作'
        ],
        'reject': [
          '审核驳回后，成绩状态将变更为"已驳回"',
          '学生需要根据驳回原因重新提交成绩',
          '驳回原因将同步通知相关学生'
        ],
        'publish': [
          '成绩公示后，所有用户均可查看成绩详情',
          '公示期间如有异议，学生可以提出申诉',
          '公示期结束后成绩状态将最终确定'
        ]
      }
      return contentMap[props.auditType] || []
    }

    const getSubmitButtonText = () => {
      const buttonMap = {
        'approve': '确认通过',
        'reject': '确认驳回',
        'publish': '确认公示'
      }
      return buttonMap[props.auditType] || '确认提交'
    }

    // 监听审核类型变化
    watch(() => props.auditType, (newVal) => {
      resetForm()
      // 设置默认结果
      if (newVal === 'approve') {
        auditForm.value.result = '通过'
      } else if (newVal === 'reject') {
        auditForm.value.result = '驳回'
      } else if (newVal === 'publish') {
        auditForm.value.result = '公示'
      }
    }, { immediate: true })

    return {
      // 响应式数据
      submitLoading,
      auditFormRef,
      auditForm,
      auditFormRules,
      rejectReasons,

      // 计算属性
      dialogVisible,
      dialogTitle,

      // 方法
      getProjectCount,
      getStudentCount,
      getAuditIcon,
      getAuditIconClass,
      getAuditTypeTag,
      getAuditTypeText,
      getStatusTagType,
      getScoreClass,
      getRankingClass,
      formatScore,
      getRemarkPlaceholder,
      getAlertTitle,
      getAlertType,
      getAlertContent,
      getSubmitButtonText,
      handleStudentClick,
      handleResultChange,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
/* 主对话框样式 */
.audit-dialog {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.audit-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.audit-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 1.5rem 2rem;
  margin: 0;
}

.audit-dialog :deep(.el-dialog__title) {
  font-size: 1.25rem;
  font-weight: 600;
  color: white;
}

.audit-dialog :deep(.el-dialog__headerbtn) {
  top: 1.5rem;
  right: 1.5rem;
}

.audit-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

.audit-dialog :deep(.el-dialog__body) {
  padding: 0;
  max-height: 80vh;
  overflow-y: auto;
}

/* 卡片样式 */
.info-card,
.form-card {
  margin: 1rem;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.info-card :deep(.el-card__header),
.form-card :deep(.el-card__header) {
  background: white;
  border-bottom: 1px solid #f0f0f0;
  padding: 1.25rem 1.5rem;
}

.info-card :deep(.el-card__body),
.form-card :deep(.el-card__body) {
  padding: 1.5rem;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.header-icon.success {
  background: linear-gradient(135deg, #10b981, #059669);
}

.header-icon.danger {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.header-icon.primary {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
}

.header-icon.info {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
}

.header-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1e293b;
}

/* 统计摘要 */
.selection-summary {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background: linear-gradient(135deg, #f8fafc, #f1f5f9);
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.summary-item {
  text-align: center;
}

.summary-number {
  font-size: 2rem;
  font-weight: 700;
  color: #3b82f6;
  line-height: 1;
  margin-bottom: 0.5rem;
}

.summary-label {
  font-size: 0.875rem;
  color: #64748b;
  font-weight: 500;
}

/* 成绩表格 */
.selected-scores {
  border-radius: 8px;
  overflow: hidden;
}

.project-cell {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.project-icon {
  color: #f59e0b;
  font-size: 16px;
}

.score-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.score-cell.gold-score {
  background: linear-gradient(135deg, #fef3c7, #fde68a);
}

.score-cell.silver-score {
  background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
}

.score-cell.bronze-score {
  background: linear-gradient(135deg, #fed7aa, #fdba74);
}

.score-value {
  font-size: 1rem;
  font-weight: 600;
  color: #1e293b;
}

.score-unit {
  font-size: 0.75rem;
  color: #64748b;
}

.ranking-badge {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.875rem;
  margin: 0 auto;
}

.ranking-badge.gold {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: white;
}

.ranking-badge.silver {
  background: linear-gradient(135deg, #d1d5db, #9ca3af);
  color: white;
}

.ranking-badge.bronze {
  background: linear-gradient(135deg, #fb923c, #f97316);
  color: white;
}

.ranking-badge.normal {
  background: #f1f5f9;
  color: #64748b;
}

/* 表单样式 */
.audit-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.audit-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  line-height: 1.6;
}

.audit-form :deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 100px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.audit-form :deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.audit-form :deep(.el-input__inner) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.audit-form :deep(.el-input__inner:focus) {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 操作按钮 */
.dialog-footer {
  padding: 1.5rem 2rem;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.dialog-footer :deep(.el-button) {
  min-width: 120px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.dialog-footer :deep(.el-button--primary) {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border: none;
}

.dialog-footer :deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
}

/* 审核提示 */
.audit-alert {
  margin: 1rem;
}

.audit-alert :deep(.el-alert__content) {
  padding: 1rem;
}

.alert-content {
  margin: 0;
  padding-left: 1.5rem;
}

.alert-content li {
  margin-bottom: 0.5rem;
  line-height: 1.6;
  color: #374151;
}

.alert-content li:last-child {
  margin-bottom: 0;
}

.text-placeholder {
  color: #c0c4cc;
}
</style>